const fs = require("fs");
const Jsons = require("./jsonClass");
const jsonClass = new Jsons();
const { createResponse, validatePaginationParams, handlePagination, handleError, handleJson } = require("./common.js");
const { searchData } = require("./search.js");
module.exports = {
  questionList: async (ctx) => {
    try {
      const filePath = ctx.state.fullPath;
      const stats = fs.statSync(filePath);
      // 读取JSON文件内容 readJsonFile
      let jsonData = jsonClass.readJsonFile(filePath);
      // 验证分页参数
      const validation = validatePaginationParams(ctx.query.current, ctx.query.size);
      if (!validation.isValid) {
        ctx.body = createResponse(false, 400, validation.error);
        return;
      }
      if (ctx.query.title) {
        jsonData = searchData(jsonData, ctx.query.title, ["title", "content"]);
      }
      if (ctx.query.category && ctx.query.category !== "全部") {
        jsonData = jsonData.filter((item) => item.category === ctx.query.category);
      }
      // 处理分页
      const paginationResult = handlePagination(jsonData, validation.page, validation.pageSize);
      ctx.body = createResponse(true, 200, "获取数据成功", paginationResult.data);
    } catch (err) {
      handleError(ctx, err, "读取JSON文件");
    }
  }
};
